package org.ws.httphelper.builder;

import com.google.common.collect.Maps;
import org.ws.httphelper.HttpHelper;
import org.ws.httphelper.builder.annotation.HttpOperation;
import org.ws.httphelper.exception.BuildException;
import org.ws.httphelper.model.template.RequestTemplate;
import org.ws.httphelper.support.DefaultHttpHelper;
import org.ws.httphelper.support.annotation.OperationProxyFactory;

import java.util.Map;

public final class HttpHelperBuilder {

    private static Map<Class, OperationProxyFactory> proxyFactoryMap = Maps.newConcurrentMap();

    private HttpHelperBuilder(){}

    public static HttpHelperBuilder builder(){
        return new HttpHelperBuilder();
    }

    /**
     *
     * @param type
     * @param <T>
     * @return
     * @throws BuildException
     */
    public <T> T builderByAnn(Class<T> type)throws BuildException {
        if (!type.isAnnotationPresent(HttpOperation.class)) {
            throw new BuildException("Can not found @HttpOperation.");
        }
        OperationProxyFactory<T> factory;
        if(proxyFactoryMap.containsKey(type)){
            factory = proxyFactoryMap.get(type);
        }
        else {
            factory = new OperationProxyFactory<>(type);
            proxyFactoryMap.put(type,factory);
        }
        return factory.newInstance();
    }

    /**
     *
     * @param template
     * @return
     */
    public HttpHelper builderByTemplate(RequestTemplate template){
        return new DefaultHttpHelper(template);
    }
}
